﻿namespace EasyCommonCore.Common
{
    /// <summary>
    /// String扩展
    /// </summary>
    public static class StringCommon
    {
        #region 得到第number次出现character的位置下标
        /// <summary>
        /// 得到第number次出现character的位置下标
        /// </summary>
        /// <param name="parameter">待匹配字符串</param>
        /// <param name="character">匹配的字符串</param>
        /// <param name="number">倒数第n次出现（默认倒数第1次）</param>
        /// <param name="defaultIndexof">默认下标-1（未匹配到）</param>
        /// <returns></returns>
        public static int IndexOf(this string parameter, char character, int number = 1, int defaultIndexof = -1)
        {
            if (string.IsNullOrEmpty(parameter))
            {
                return defaultIndexof;
            }
            string temp = "";
            int count = 1;//第1次匹配
            while (count < number)
            {
                var index = parameter.IndexOf(character);
                temp = temp.Substring(index, parameter.Length - index);
                count++;
            }
            return temp.IndexOf(character);
        }
        #endregion

        #region 得到倒数第number次出现character的位置下标
        /// <summary>
        /// 得到倒数第number次出现character的位置下标
        /// </summary>
        /// <param name="parameter">待匹配字符串</param>
        /// <param name="character">匹配的字符串</param>
        /// <param name="number">倒数第n次出现（默认倒数第1次）</param>
        /// <param name="defaultIndexof">默认下标-1（未匹配到）</param>
        /// <returns></returns>
        public static int LastIndexOf(this string parameter, char character, int number = 1, int defaultIndexof = -1)
        {
            if (string.IsNullOrEmpty(parameter))
            {
                return defaultIndexof;
            }
            string temp = "";
            int count = 1;//第1次匹配
            while (count < number)
            {
                temp = temp.Substring(0, parameter.LastIndexOf(character));
                count++;
            }
            return temp.LastIndexOf(character);
        }
        #endregion
    }
}
